require('./index.css');
var _util = require('../../util/util.js');
var _account_service = require('service/account-service.js');
var _header = require('page/common/header/index.js');
var vCode;

var userInformation = {
    init : function(){
        $('#messageAccount').hide();
        $('#usernameTips').hide();
        $('#passwordTips').hide();
        $('#usernameTr').hide();
        $('#passwordTr').hide();
        this.code_draw();
        this.bindEvents();
        return this;
    },
    bindEvents : function(){
        var _this = this;
        $('#canvas').click(
            function(){
                _this.code_draw();
            }
        )
        $('#newAccount').click(
            function(){
                _this.register();
            }
        ),
        $('#username').blur(
            function(){
                $('#messageAccount').hide();
                if($.trim($('#username').val()) == ""){
                    $('#usernameTr').hide();
                    $('#usernameTips').hide();
                }else{
                    _account_service.usernameExist(
                        {
                            "username" :$.trim($('#username').val()),
                        },  
                        function(res){
                            if(res == "用户名已存在"){
                                $('#usernameTips').css('color','red');
                            }else{
                                $('#usernameTips').css('color','green');
                            }
                            $('#usernameTr').show();
                            $('#usernameTips').show().text(res);
                        },
                        function(errMsg){
                            $('#usernameTr').show();
                            $('#usernameTips').show().text(errMsg);
                        });
                }
            }
        );
        $('#repeatedPassword').blur(
            function(){
                $('#messageAccount').hide();
                if($.trim($('#repeatedPassword').val()) == ""){
                    $('#passwordTr').hide();
                    $('#passwordTips').hide();
                }
                else if($.trim($('#password').val()) == ""){
                    $('#passwordTips').css('color','red');
                    $('#passwordTr').show();
                    $('#passwordTips').show().text("密码未输入");
                }
                else if($.trim($('#password').val()) == $.trim($('#repeatedPassword').val())){
                    $('#passwordTips').css('color','green');
                    $('#passwordTr').show();
                    $('#passwordTips').show().text("密码正确");
                }else{
                    $('#passwordTips').css('color','red');
                    $('#passwordTr').show();
                    $('#passwordTips').show().text("两次输入的密码不一致");
                }
            }
        );
        $('#vCode').blur(
            function(){
                $('#messageAccount').hide();
                if(!($.trim($('#vCode').val().toLowerCase()) == vCode)){
                    console.log("验证码错误");
                }else{
                    console.log("验证码正确");
                }
            }
        )
    },
    formValidation : function(){
        var result = {
            status : false,
            msg    : ''
        };
        if(!_util.validateField('require',$.trim($('#username').val()))){
            result.msg = '用户名不能为空';
            return result;
        }
        if(!_util.validateField('require',$.trim($('#password').val()))){
            result.msg = '密码不能为空';
            return result;
        }
        if(!_util.validateField('require',$.trim($('#repeatedPassword').val()))){
            result.msg = '确认密码不能为空';
            return result;
        }
        if(!($.trim($('#password').val()) == $.trim($('#repeatedPassword').val()))){
            result.msg = '两次密码不一致';
            return result;
        }
        if(!(($.trim($('#vCode').val()) == vCode)||($.trim($('#vCode').val().toLowerCase()) == vCode))){
            result.msg = '验证码错误';
            return result;
        }
        //校验通过
        result.status = true;
        result.msg = '校验通过';
        return result;
    },
    register : function(){
        var validationResult = this.formValidation();
        if(validationResult.status){
            var accountVO = {
                username : $.trim($('#username').val()),
                password : $.trim($('#password').val()),
                email    : $.trim($('#email').val()),
                firstName: $.trim($('#firstName').val()),
                lastName : $.trim($('#lastName').val()),
                status   : "",
                address1 : $.trim($('#address1').val()),
                address2 : $.trim($('#address2').val()),
                city     : $.trim($('#city').val()),
                state    : $.trim($('#state').val()),
                zip      : $.trim($('#zip').val()),
                country  : $.trim($('#country').val()),
                phone    : $.trim($('#phone').val()),
                favouriteCategoryId: $('#favouriteCategoryId').find('option:selected').val(),
                languagePreference : $('#languagePreference').find('option:selected').val(),
                listOption   :Boolean($('#listOption').prop("checked")),
                bannerOption :Boolean($('#bannerOption').prop("checked")),
                bannerName   : ""
            };
            console.log(accountVO);
            _account_service.register(
                accountVO,
                function(res){
                    window.location.href='./catalog-main.html';
                },
                function(errMsg){
                    $('#messageAccount').show().text(errMsg);
                    $('#passwordTr').hide();
                    $('#usernameTr').hide();
                    $('#usernameTips').hide();
                    $('#passwordTips').hide();
                }
                );
        }else{
            $('#messageAccount').show().text(validationResult.msg);
            $('#passwordTr').hide();
            $('#passwordTips').hide();
        }
    },
    code_draw : function(){
    var _this = this;
    var canvas_width = $('#canvas').width();
	var canvas_height = $('#canvas').height();
	var canvas = document.getElementById("canvas"); //获取到canvas的对象，演员
	var context = canvas.getContext("2d"); //获取到canvas画图的环境，演员表演的舞台
	canvas.width = canvas_width;
	canvas.height = canvas_height;
	var sCode = "A,B,C,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0"; //取值范围
	var aCode = sCode.split(",");
	var aLength = aCode.length; //获取到数组的长度
	var value = [];
	for (var i = 0; i <= 3; i++) {
		var j = Math.floor(Math.random() * aLength); //获取到随机的索引值
		var deg = Math.random() * 30 * Math.PI / 180; //产生0~30之间的随机弧度
		var txt = aCode[j]; //得到随机的一个内容
		value[i] = txt.toLowerCase();
		var x = 10 + i * 20; //文字在canvas上的x坐标
		var y = 20 + Math.random() * 8; //文字在canvas上的y坐标
		context.font = "bold 23px 微软雅黑";
		context.translate(x,y);
		context.rotate(deg);
		context.fillStyle = _this.code_randomColor();
		context.fillText(txt,0,0);
		context.rotate(-deg);
		context.translate(-x,-y);
	}
	// 将生成的值以属性的方法添加到元素
	value = value.join("");
	$('#canvas').attr('data-code',value)
	//验证码上显示线条
	for (var i = 0; i <= 5; i++) {
		context.strokeStyle = _this.code_randomColor();
		context.beginPath();
		context.moveTo(Math.random() * canvas_width,Math.random() * canvas_height);
		context.lineTo(Math.random() * canvas_width,Math.random() * canvas_height);
		context.stroke();
	}
	//验证码上显示小点
	for (var i = 0; i <= 30; i++) {
		context.strokeStyle = _this.code_randomColor();
		context.beginPath();
		var x = Math.random() * canvas_width;
		var y = Math.random() * canvas_height;
		context.moveTo(x,y);
		context.lineTo(x + 1,y + 1);
		context.stroke();
	 }
     vCode = value;
    },
    code_randomColor : function(){
        var r = Math.floor(Math.random() * 256);
    var g = Math.floor(Math.random() * 256);
    var b = Math.floor(Math.random() * 256);
    return "rgb(" + r + "," + g + "," + b + ")";
    }
};

module.exports = userInformation.init();